import { Command, CommandRunner } from 'nest-commander';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from '../modules/role/entities/role.entity';
import { User } from '../modules/user/entities/user.entity';

@Command({
  name: 'init:admin',
  description: '初始化管理员用户和角色'
})
export class InitAdminCommand extends CommandRunner {
  constructor(
    @InjectRepository(Role)
    private roleRepository: Repository<Role>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {
    super();
  }

  async run(): Promise<void> {
    console.log('开始初始化管理员用户和角色...');
    
    // 创建或获取管理员角色
    let adminRole = await this.roleRepository.findOne({
      where: { code: 'SUPER_ADMIN' }
    });

    if (!adminRole) {
      adminRole = this.roleRepository.create({
        code: 'SUPER_ADMIN',
        name: '超级管理员',
        description: '系统超级管理员角色'
      });
      await this.roleRepository.save(adminRole);
      console.log('✓ 管理员角色创建成功');
    } else {
      console.log('✓ 管理员角色已存在');
    }

    // 创建或检查管理员用户
    const adminUser = await this.userRepository.findOne({
      where: { username: 'admin' }
    });

    if (!adminUser) {
      const newUser = this.userRepository.create({
        username: 'admin',
        password: '123456', // 密码将在保存时自动加密
        role: adminRole
      });
      await this.userRepository.save(newUser);
      console.log('✓ 管理员用户创建成功，用户名: admin, 密码: 123456');
    } else {
      console.log('✓ 管理员用户已存在');
    }

    console.log('初始化完成！');
  }
}
